<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId" @submit.prevent>
        <el-form-item label="应用名称" prop="app_name">
          <el-input placeholder="请输入应用名称" v-model="searchParams.app_name" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="APP_KEY" prop="APP_KEY">
          <el-input placeholder="请输入应用名称" v-model="searchParams.app_key" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <el-table v-loading="loading" v-adaptive border :data="tableList" empty-text="暂时没有数据哟">
        <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
        <el-table-column label="应用名称" prop="app_name" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="APP_KEY" prop="app_key" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="APP_SECRET" prop="app_secret" align="center"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="状态" prop="status" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.status ? '启用' : "停用" }}
          </template>
        </el-table-column>
        <el-table-column label="是否限流" prop="is_limit" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.is_limit ? scope.row.limit + "次 / " + scope.row.window_time + "秒" : "不限流" }}
          </template>
        </el-table-column>
        <el-table-column label="授权模块" prop="module" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" align="left" fixed="right" v-auth="['system:role:update', 'system:role:delete']">
          <template #default="{ row }">
            <el-button type="primary" size="small" plain @click="handleUpdate(row)" v-auth="['system:role:update']">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- 分页 -->
      <el-pagination background v-model:current-page="searchParams.pageNo" v-model:page-size="searchParams.pageSize"
        v-show="total > 0" :page-sizes="[10, 20, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper"
        :total="total" @size-change="handleListPage" @current-change="handleListPage" />

      <!-- 添加 OR 修改 -->
      <KoiDrawer ref="koiDrawerRef" :title="title" @koi-confirm="handleConfirm" @koi-cancel="handleCancel"
        :loading="confirmLoading" :size="1000">
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="120px" status-icon>
            <el-form-item label="应用名称" prop="app_name" help="应用名称xxxxxxxx">
              <el-input v-model="form.app_name" placeholder="请输入应用" clearable />
            </el-form-item>
            <el-form-item label="APP_KEY" prop="app_key">
              <el-input v-model="form.app_key" placeholder="请输入APP_KEY" clearable />
            </el-form-item>
            <el-form-item label="app_secret" prop="app_secret">
              <el-input v-model="form.app_secret" placeholder="请输入APP_SECRET" clearable />
            </el-form-item>
            <el-form-item label="授权模块" prop="module">
              <el-input v-model="form.module" placeholder="请输入模块 如:cms 用于限制权限" clearable />
            </el-form-item>
            <el-form-item label="IP白名单" prop="white_ip_list">
              <el-input type="textarea" rows='3' v-model="form.white_ip_list" placeholder="请输入IP ,不输入不限制白名单 使用逗号隔开如192.108.1.1,192.108.1.2" clearable />
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" active-text="启用" inactive-text="停用" :active-value="1" :inactive-value="0"
                :inline-prompt="true">
              </el-switch>
            </el-form-item>
            <el-form-item label="是否限流" prop="is_limit">
              <el-switch v-model="form.is_limit" active-text="开启限流" inactive-text="关闭限流" :active-value="1"
                :inactive-value="0" :inline-prompt="true">
              </el-switch>
            </el-form-item>
            <div v-if="form.is_limit == 1">
              <el-form-item label="限流配置" prop="limit">
                <el-row>
                  <el-col :span="11">
                    <el-input v-model="form.window_time" placeholder="请输入限流时间 如:60" >
                      <template #append>
                        秒内
                      </template>
                    </el-input>
                  </el-col>
                  -
                  <el-col :span="11">
                    <el-input v-model="form.limit" placeholder="请输入请求次数 如:200" >
                      <template #append>
                        次
                      </template>
                    </el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </div>
          </el-form>
        </template>
      </KoiDrawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="memberLevelPage">
import { onMounted, reactive, ref } from "vue";
import { koiMsgError, koiMsgWarning, koiNoticeError } from "@/utils/koi.ts";
import { add, read, listPage, update } from "@/plugin/coleopenapi/api/app/index.ts";

import { koiDatePicker } from "@/utils/index.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  app_name: "",
  app_key: "",
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    app_name: "",
    app_key: "",
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

// 时间
const dateRange = ref();
/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value, "created"));
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
});

/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "添加";
  koiDrawerRef.value.koiOpen();
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await read(id);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "修改";
  const id = row.id
  if (id == null || id == "") {
    koiMsgError("请选中需要修改的数据");
  }
  handleEcho(id);
  koiDrawerRef.value.koiOpen();
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("用户类型管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  app_name: "",
  app_key: "",
  app_secret: "",
  status: 1,
  limit: 0,
  window_time: 0,
  is_limit: 0,
  module: ""
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    app_name: "",
    app_key: "",
    app_secret: "",
    status: 1,
    limit: 0,
    window_time: 0,
    is_limit: 0,
    module: ""
  };
};

/** 表单规则 */
const rules = reactive({
  app_name: [{ required: true, message: "请输入APP名称", trigger: "blur" }],
  app_key: [{ required: true, message: "请输入APP_KEY", trigger: "blur" }],
  app_secret: [{ required: true, message: "请选择APP_SECRET", trigger: "blur" }],
  status: [{ required: true, message: "请输入状态", trigger: "blur" }],
  module: [{ required: true, message: "请输入授权模块", trigger: "blur" }],
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      try {
        if (form.value.id != null && form.value.id != "") {
          await update(form.value);
        } else {
          await add(form.value);
        }
        resetForm();
        handleListPage();
        koiDrawerRef.value.koiQuickClose();
      } catch (error) {
        console.log(error);
        confirmLoading.value = false;
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        confirmLoading.value = false;
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

</script>

<style lang="scss" scoped></style>
